//
//  KXChannelsPresenter.swift
//  YunshuApp
//
//  Created by 周文杰 on 2017/6/2.
//  Copyright © 2017年 zwj. All rights reserved.
//

import UIKit
import HandyJSON
import PullToRefresh

class KXChannelsPresenter: NSObject ,UITableViewDelegate, UITableViewDataSource{

    let view = UITableView.init(frame: CGRect.init(x: 0, y: 0,
                                                   width: Const.SCREEN_WIDTH,
                                                   height: Const.SCREEN_HEIGHT - 132),
                                style: .plain)
    var models : [KXChannel] = []
    var pageNum = 0
    let bottomRefreher = PullToRefresh(position: .bottom)

    var singleSelect = false
    var selected:[KXChannel] = []
    
    deinit {
        if let head = view.topPullToRefresh{
            self.view.removePullToRefresh(at: .top)
        }
        if let btm = view.bottomPullToRefresh{
            self.view.removePullToRefresh(at: .bottom)

        }
    }
    
    override init() {
        super.init()
        
        self.view.delegate = self
        self.view.dataSource = self
        self.refresh()
    }
    
    func relayout() {
        self.setupPullToRefresh()
    }
    
    func setupPullToRefresh() {
        self.view.addPullToRefresh(PullToRefresh()) { [weak self] in
            self?.refresh()
        }
        self.addRefreshFooter()
    }
    
    func addRefreshFooter() -> Void {
        self.view.addPullToRefresh(bottomRefreher) { [weak self] in
            if self == nil {
                return
            }
            self!.loadmore()
        }
    }
    
    func refresh() {
        let params = ["page":"1"]
        
        _ = NetworkManager.GET(NetworkManager.Kuaixun_Channels,params: params) {
            (status, response) in
            //            result.get("pic")
            //            updateBanner(pics);
            self.view.endRefreshing(at: .top)
            if status {
                let newKuaixuns = response.wtmList.map({ (dic) -> KXChannel in
                    let channel = JSONDeserializer<KXChannel>.deserializeFrom(dict:dic as? NSDictionary)!
                    channel.channelId = channel.title
                    channel.isSelected = self.selected.filter({ c in
                        c.title == channel.title
                    }).count > 0
                    return channel
                })
                self.models.removeAll()
                self.models.append(contentsOf: newKuaixuns)
                self.pageNum = 2
                self.view.reloadData()
            }
        }
    }
    
    func loadmore() {
        let pageNumStr = String(pageNum)
        let params = ["page":pageNumStr]
        
        _ = NetworkManager.GET(NetworkManager.Kuaixun_Channels,params: params) {
            (status, response) in
            //            result.get("pic")
            //            updateBanner(pics);
            self.view.endRefreshing(at: .bottom)
            if status {
                let newKuaixuns = response.wtmList.map({ (dic) -> KXChannel in
                    let channel = JSONDeserializer<KXChannel>.deserializeFrom(dict:dic as? NSDictionary)!
                    channel.isSelected = self.selected.filter({ c in
                        c.title == channel.title
                    }).count > 0
                    return channel
                })
                self.models.append(contentsOf: newKuaixuns)
                self.pageNum += 1
                self.view.reloadData()
            }
        }
    }
    
    // MARK :- tableView
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return models.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let reuseId = "banner"
        let model = models[indexPath.row]
        if let cell = tableView.dequeueReusableCell(withIdentifier: reuseId) as? KXChannelCell {
            cell.button.isSelected = model.isSelected
            cell.textLabel?.text = model.title
            cell.selectionStyle = .none
            return cell
        }
        let cell = KXChannelCell.init(style: .default, reuseIdentifier: reuseId)
        cell.contentView.backgroundColor = UIColor.white
        cell.textLabel?.text = model.title
        cell.button.isSelected = model.isSelected
        cell.selectionStyle = .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = models[indexPath.row]
        if self.singleSelect { //单选
            _=self.models.map({ c in
                c.isSelected = false
            })
            model.isSelected = true
            self.selected = [model]
        }else{ //多选
            if model.isSelected {
                model.isSelected = false
                selected = selected.filter({ c in
                    c.channelId != model.channelId
                })
            }else{
                model.isSelected = true
                selected.append(model)
            }
        }
        self.view.reloadData()
    }
}
